package com.qf.shop.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.Map;

@Slf4j
public class JWTUtils {

    private static final String sign = "2103-shop"; // 签名

    /**
     * 生成token
     *
     * @param map  载荷
     * @param time tokne的过期时间，单位毫秒
     * @return
     */
    public static String createToken(Map<String, String> map, int time) {
        JWTCreator.Builder builder = JWT.create();

        // 1.设置载荷
        for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
            String key = stringStringEntry.getKey();
            String value = stringStringEntry.getValue();
            builder.withClaim(key, value);
        }

        // 2.设置Token的过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MILLISECOND, time);
        builder.withExpiresAt(calendar.getTime());

        // 3.设置签名
        return builder.sign(Algorithm.HMAC256(sign));
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static DecodedJWT checkToken(String token) {
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(sign)).build().verify(token);
            return verify;
        } catch (SignatureVerificationException e) {
            log.error("token验证失败了，签名不一致");
        } catch (AlgorithmMismatchException e) {
            log.error("token验证失败了，签名算法不一致");
        } catch (TokenExpiredException e) {
            log.error("token验证失败了，token过期了");
        } catch (Exception e) {
            log.error("token校验失败", e);
        }
        return null;
    }

    /**
     * 获取Token中的内容
     *
     * @param key
     * @return
     */
    public static String getData(DecodedJWT verify, String key) {
        return verify.getClaim(key).asString();
    }
}
